package com.kun.kunkunmall.ware.listener;

import com.alibaba.fastjson.TypeReference;
import com.kun.common.to.OrderTo;
import com.kun.common.to.StockDetailTo;
import com.kun.common.to.StockLockedTo;
import com.kun.common.utils.R;
import com.kun.kunkunmall.ware.dao.WareSkuDao;
import com.kun.kunkunmall.ware.entity.WareOrderTaskDetailEntity;
import com.kun.kunkunmall.ware.entity.WareOrderTaskEntity;
import com.kun.kunkunmall.ware.feign.OrderFeignService;
import com.kun.kunkunmall.ware.service.WareOrderTaskDetailService;
import com.kun.kunkunmall.ware.service.WareOrderTaskService;
import com.kun.kunkunmall.ware.service.WareSkuService;
import com.kun.kunkunmall.ware.vo.OrderVo;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

@RabbitListener(queues = "stock.release.stock.queue")
@Component
public class StockReleaseListener {

    @Autowired
    private WareSkuService wareSkuService;

    /**
     * 释放库存
     * 1. 下订单成功，库存锁定成功，接下来的业务调用失败，导致订单回滚，此时库存不会回滚，这时候需要手动去释放库存。
     * 2. 库存锁定失败，此时库存会自动回滚，无需手动释放库存。
     */
    @RabbitHandler
    public void releaseLockStock(StockLockedTo stockLockedTo, Message message, Channel channel) throws IOException, TimeoutException {

        try {
            wareSkuService.unlockWareStock(stockLockedTo, message, channel);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
        }
    }

    @RabbitHandler
    public void releaseOrderClose(OrderTo to, Message message, Channel channel) throws IOException {
        System.out.println("订单关闭，准备解锁库存");
        try {
            wareSkuService.unlockWareStock(to);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (Exception e) {
            channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
        }

    }


}
